<template>
  <div>
    <el-row>
      <el-card>
        <div style="margin-top: 15px;" id="app">
          <el-form :inline="true" :model="selectForm" class="demo-form-inline" ref="selectFormRef">
            <el-select v-model="selectForm.areaRole" placeholder="区域类型" style="width: 15%">
              <el-option label="校门" value="A"></el-option>
              <el-option label="宿舍楼" value="B"></el-option>
              <el-option label="教学楼" value="C"></el-option>
              <el-option label="行政楼" value="D"></el-option>
              <el-option label="图书馆" value="E"></el-option>
            </el-select>
            <el-input
                    v-model="selectForm.areaName"
                    placeholder="请输入区域名称"
                    style="width: 15%"
            ></el-input>
            <el-select v-model="selectForm.personRole" placeholder="人员类型" style="width: 15%">
              <el-option label="外来人员" value=0></el-option>
              <el-option label="本科生" value=1></el-option>
              <el-option label="研究生" value=2></el-option>
              <el-option label="教工" value=3></el-option>
              <el-option label="职工" value=4></el-option>
            </el-select>
            <el-input
                    v-model="selectForm.personName"
                    placeholder="请输入人员名称"
                    style="width: 15%"
            ></el-input>
            <el-date-picker
                    v-model="selectForm.recordDate"
                    type="date"
                    placeholder="选择日期"
                    style="width: 15%">
            </el-date-picker>
            <el-button type="primary" @click="select()">查询</el-button>
            <el-button type="primary" @click="resetSelect()">重置</el-button>
          </el-form>
          <el-table
                  v-loading="loading"
                  :data="tableData"
                  @selection-change="handleSelectionChange"
                  style="width: 100%"
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column
                    label="人员名称"
                    sortable
                    width="100"
            >
              <template slot-scope="scope">
                <span>{{scope.row.person_name}}</span>
              </template>
            </el-table-column>
            <el-table-column
                    label="区域名称"
                    sortable
                    width="150"
            >
              <template slot-scope="scope">
                <span>{{scope.row.area_name}}</span>
              </template>
            </el-table-column>
            <el-table-column
                    label="通行状态"
                    sortable
                    width="200"
            >
              <template slot-scope="scope">
                <p v-if="scope.row.status == 'A'">正常</p>
                <p v-if="scope.row.status == 'B'">非正常时间进出</p>
                <p v-if="scope.row.status == 'C'">越权进出</p>
              </template>
            </el-table-column>
            <el-table-column prop="direction" label="进出" sortable width="100">
              <template slot-scope="scope">
                <p v-if="scope.row.direction == 'A'">进入</p>
                <p v-if="scope.row.direction == 'B'">离开</p>
              </template>
            </el-table-column>
            <el-table-column
                    label="通行时间"
                    sortable
                    width="200"
            >
              <template slot-scope="scope">
                <span>{{scope.row.recordDate}}</span>
              </template>
            </el-table-column>
            <el-table-column align="right" width="70">
              <template slot="header">
                <el-button type="primary" @click="save = true" size="mini" plain
                >添加</el-button
                >
              </template>
            </el-table-column>
            <el-table-column align="right" width="130">
              <template slot="header">
                <el-button
                        type="primary"
                        @click="exportExcel()"
                        size="mini"
                        plain
                >导出所选中信息</el-button
                >
              </template>
            </el-table-column>
            <el-table-column align="right" width="150">
              <template slot="header">
                <el-button
                        type="danger"
                        @click="deleteMessages()"
                        size="mini"
                        plain
                >删除所选中信息</el-button
                >
              </template>
              <template slot-scope="scope">
                <el-button
                        size="mini"
                        type="primary"
                        plain
                        @click="(edit = true), getForm(scope.row.id)"
                        v-if="scope.row && update_button == 1"
                >修改
                </el-button>
                <el-button
                        size="mini"
                        type="danger"
                        plain
                        @click="deleteRecord(scope.row)"
                        v-if="scope.row && delete_button == 1"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
                  style="margin: 15px 0px;"
                  prev-text="上一页"
                  next-text="下一页"
                  background
                  layout="prev, pager, next, sizes, jumper, total"
                  :page-sizes="[5, 10, 20, 40, 100, 500, 50000]"
                  :page-size="pageSize"
                  :total="total"
                  :current-page="pageNow"
                  @current-change="findPage"
                  @size-change="findSize"
          >
          </el-pagination>
          <el-dialog :visible.sync="openImg" width="400px">
            <img src="http://localhost:9000/Code/createCommonQRCode" style="" />
          </el-dialog>

          <el-dialog title="添加通行记录" :visible.sync="save" width="24%">
            <el-form ref="sForm" label-width="80px" :model="saveForm">
              <el-form-item label="人员id" prop="p_id">
                <el-input v-model="saveForm.pid"style="width: 220px"></el-input>
              </el-form-item>
              <el-form-item label="区域id" prop="a_id">
                <el-input v-model="saveForm.aid"style="width: 220px"></el-input>
              </el-form-item>
              <el-form-item label="通行状态" prop="status">
                <el-select v-model="saveForm.status" placeholder="通行状态">
                  <el-option label="正常" value="A"></el-option>
                  <el-option label="非正常时间进出" value="B"></el-option>
                  <el-option label="越权进出" value="C"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="进出" prop="direction">
                <el-select v-model="saveForm.direction" placeholder="进出">
                  <el-option label="进入" value="A"></el-option>
                  <el-option label="离开" value="B"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="通行时间:">
                <div class="block">
                  <el-date-picker
                          v-model="saveForm.recordDate"
                          type="datetime"
                          placeholder="选择日期时间"
                          align="right"
                          format="yyyy-MM-dd HH:mm"
                          :picker-options="pickerOptions"
                  >
                  </el-date-picker>
                </div>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="save = false">取 消</el-button>
              <el-button
                      type="primary"
                      @click="(save = false), saveRecord('sForm')"
              >确 定</el-button
              >
            </span>
          </el-dialog>
          <el-dialog title="修改通行信息" :visible.sync="edit" width="24%">
            <el-form ref="editForm" label-width="80px" :model="eform">
              <el-form-item label="人员id" prop="pId">
                <el-input v-model="eform.pid" disabled style="width: 220px"></el-input>
              </el-form-item>
              <el-form-item label="区域id" prop="aId">
                <el-input v-model="eform.aid" disabled style="width: 220px"></el-input>
              </el-form-item>
              <el-form-item label="通行状态" prop="status">
                <el-select v-model="eform.status" placeholder="通行状态">
                  <el-option label="正常" value="A"></el-option>
                  <el-option label="非正常时间进出" value="B"></el-option>
                  <el-option label="越权进出" value="C"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="进出" prop="direction">
                <el-select v-model="eform.direction" placeholder="进出">
                  <el-option label="进入" value="A"></el-option>
                  <el-option label="离开" value="B"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="通行时间:">
                <div class="block">
                  <el-date-picker
                          v-model="eform.recordDate"
                          type="datetime"
                          placeholder="选择日期时间"
                          align="right"
                          format="yyyy-MM-dd HH:mm"
                          :picker-options="pickerOptions"
                  >
                  </el-date-picker>
                </div>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="edit = false">取 消</el-button>
              <el-button
                      type="primary"
                      @click="(edit = false), updateRecord('editForm')"
              >确 定</el-button
              >
            </span>
          </el-dialog>
        </div>
      </el-card>
    </el-row>
    <el-row>
      <el-divider content-position="left">Excel 导入</el-divider>
      <el-card>
        <el-row class="mb20">
          <el-upload
                  action="/xxx/xxx"
                  accept=".xls, .xlsx"
                  :on-change="impotExcel"
                  :auto-upload="false"
                  multiple
                  :limit="1"
                  :file-list="fileList"
          >
            <el-button size="small" :plain="true" type="primary"
            >点击上传</el-button
            >
            <div slot="tip" class="el-upload__tip">
              只能上传 .xls .xlsx 文件，且不超过500kb
            </div>
          </el-upload>
          <el-button size="small" type="primary" @click="getMessage()"
          >确认保存</el-button
          >
        </el-row>
      </el-card>
    </el-row>
  </div>
</template>

<script>
  import echarts from "echarts";
  import XLSX from "xlsx";
  import format from "@/plugins/format.js";

  var list = [];

  /* 银行账户 */
  export function validateAccountNumber(str) {
    const reg = /^([1-9]{1})$/;
    return reg.test(str);
  }

  export default {
    data() {
      let num = /^(0|\+?[1-9][0-9]*)$/;
      let isNum = (rule, value, callback) => {
        if (!num.test(value)) {
          return callback(new Error("格式错误"));
        } else {
          callback();
        }
      };
      let percent = /^(?:[1-9]?\d|100)$/;
      let isPercent = (rule, value, callback) => {
        if (!percent.test(value)) {
          return callback(new Error("请输入0-100的整数"));
        } else {
          callback();
        }
      };
      const _this = this;
      return {
        fileList: [],
        save: false,
        edit: false,
        openImg: false,
        delete_button: 1,
        update_button: 1,
        total: 0, //总页数，从后台查询
        pageNow: 1, //当前页数，默认为1
        pageSize: 5, //当前页显示的数据条数，默认为5
        loading: false,
        tableData: null,
        selectData: [],
        selectData2: [],
        saveForm: {
          id: "",
          pid: "",
          aid: "",
          status: "",
          direction: "",
          recordDate: "",
        },
        eform: {
          id: "",
          pid: "",
          aid: "",
          status: "",
          direction: "",
          recordDate: "",
        },
        selectForm: {
          id: null,
          areaRole: null,
          areaName: null,
          personRole: null,
          personName: null,
          recordDate: null,
        },
        pickerOptions: {
          shortcuts: [
            {
              text: "今天",
              onClick(picker) {
                picker.$emit("pick", new Date());
              },
            },
            {
              text: "昨天",
              onClick(picker) {
                const date = new Date();
                date.setTime(date.getTime() - 3600 * 1000 * 24);
                picker.$emit("pick", date);
              },
            },
            {
              text: "一周前",
              onClick(picker) {
                const date = new Date();
                date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit("pick", date);
              },
            },
          ],
        },
      };
    },
    mounted() {},
    methods: {
      findAllTableDataByPage() {
        const _this = this;
        let pageRequest = {
          pageNow: this.pageNow,
          pageSize: this.pageSize,
        };
        this.$http.record.findPage(pageRequest).then((res) => {
          this.tableData = res.data;
          for (let i=0;i<this.tableData.length;i++){
            this.tableData[i].person_name = res.data[i].person.name;
            this.tableData[i].area_name = res.data[i].area.name;
          }
          this.total = res.total;
        });
      },
      impotExcel(file, fileList) {
        let that = this;
        let f = file.raw;
        let x;
        let reader = new FileReader();
        reader.onload = function(e) {
          let data = new Uint8Array(e.target.result);
          var workbook = XLSX.read(data, { type: "array" });
          let json = XLSX.utils.sheet_to_json(workbook.Sheets.Sheet1); // 取第一个sheet
          that.jsonData = json;
          x = json;
          that.jsonStr = JSON.stringify(json);
          that.tableData = json;
        };
        //this.$http.post("/studentMessage/save",message);
        reader.readAsArrayBuffer(f);
        this.$message({
          message: "Excel内信息已展示至表格内",
          type: "success",
        });
        this.delete_button = 0;
        this.update_button = 0;
      },
      getMessage() {
        this.$confirm("此操作将保存进数据库, 是否继续?", "提示", {
          confirmButtonText: "继续",
          cancelButtonText: "取消",
          type: "warning",
        })
                .then(() => {
                  this.$message({
                    type: "success",
                    message: "保存成功!",
                  });
                  this.$http.record.saveFromExcel(this.jsonData).then(function(resp) {
                    if (resp.code == 2000) location.reload();
                  });
                })
                .catch(() => {
                  this.$message({
                    type: "info",
                    message: "已取消保存",
                  });
                });
      },
      findPage(page) {
        // console.log('当前页数：' + page)
        this.pageNow = page;
        this.findAllTableDataByPage();
      },
      findSize(size) {
        // console.log('当前页面记录条数：' + size)
        this.pageSize = size;
        this.findAllTableDataByPage();
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
        //console.log(val)
      },
      saveRecord(formName) {
        const _this = this;
        this.saveForm.id = Date.parse(new Date());
        this.saveForm.recordDate = format(
                this.saveForm.recordDate,
                "YYYY-MM-DD HH:mm"
        );
        this.$http.record.save(_this.saveForm).then(function(resp) {
          if (resp.code == 2000) {
            _this.$message.success("添加成功");
            location.reload();
          } else {
            _this.$message.error("添加失败，信息错误");
          }
        });
      },
      updateRecord(formName) {
        const _this = this;
        this.eform.recordDate = format(this.eform.recordDate, "YYYY-MM-DD HH:mm");
        this.$http.record.update(this.eform).then((resp) => {
          if (resp.code == 2000) _this.$message.success("修改成功");
          location.reload();
        });
      },
      getForm(id) {
        const _this = this;
        this.$http.record.findOne(id).then((resp) => {
          _this.eform = resp.data;
          //console.log(_this.eform)
        });
      },
      deleteRecord(row) {
        this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
                .then(() => {
                  this.$http.record.del(row.id).then((resp) => {
                    if (resp.code == 2000) location.reload();
                  });

                  this.$message({
                    type: "success",
                    message: "删除成功!",
                  });
                })
                .catch(() => {
                  this.$message({
                    type: "info",
                    message: "已取消删除",
                  });
                });
        const _this = this;
      },
      deleteMessages() {
        this.$confirm("此操作将永久删除数据, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
                .then(() => {
                  this.$message({
                    type: "success",
                    message: "删除成功!",
                  });
                  this.$http.record.delMgs(this.multipleSelection).then(function(resp) {
                    if (resp.code == 2000) location.reload();
                  });
                })
                .catch(() => {
                  this.$message({
                    type: "info",
                    message: "已取消删除",
                  });
                });
      },
      exportExcel() {
        //创建book
        var wb = XLSX.utils.book_new();
        //json转sheet
        var ws = XLSX.utils.json_to_sheet(this.multipleSelection, {});
        //设置列宽
        ws["!cols"] = [{ width: 15 }, { width: 15 }, { width: 30 }];
        var timestamp = new Date().getTime();
        //sheet写入book
        XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
        //输出
        XLSX.writeFile(wb, "file_" + timestamp + ".xlsx");
      },
      select() {
        this.selectForm.recordDate=format(
                this.selectForm.recordDate,
                "YYYY-MM-DD"
        )
        //console.log("111111".indexOf("1"))//0相同 -1不同
        console.log(this.selectForm)
        let list=[];
        const _this = this;
        let pageRequest = {
          pageNow: 1,
          pageSize: 100000,
        };
        this.$http.record.findPage(pageRequest).then((res) => {
          //console.log()
          this.tableData = res.data;
          for (let i=0;i<this.tableData.length;i++){
            this.tableData[i].person_name = res.data[i].person.name;
            this.tableData[i].area_name = res.data[i].area.name;
          }
          this.total = res.total;
          for (let i=0;i<this.tableData.length;i++){
            if(
                    (
                            this.selectForm.areaRole==null
                            ||this.tableData[i].area.role.indexOf(this.selectForm.areaRole)==0
                    )
                    &&(
                            this.selectForm.areaName==null
                            ||this.tableData[i].area.name.indexOf(this.selectForm.areaName)==0
                    )
                    &&(
                            this.selectForm.personRole==null
                            ||this.tableData[i].person.role==parseInt(this.selectForm.personRole)
                    )
                    &&(
                            this.selectForm.personName==null
                            ||this.tableData[i].person.name.indexOf(this.selectForm.personName)==0
                    )
                    &&(
                            this.selectForm.recordDate==null
                            ||this.tableData[i].recordDate.indexOf(this.selectForm.recordDate)==0
                    )
            ){
              list.push(this.tableData[i])
            }
          }
          this.tableData=list
        });
      },
      resetSelect(){
        this.selectForm= {
          id: null,
          areaRole: null,
          areaName: null,
          personRole: null,
          personName: null,
          recordDate: null,
        },
                this.findAllTableDataByPage();
      },
    },
    created() {
      const _this = this;
      _this.findAllTableDataByPage();
    },
  };
</script>

<style scoped></style>
